<template>
  <div class="filter-model">
    <i class="myicon icon-filter"></i>
    <template v-for="(tag,i) in filterData">
      <el-tag
        v-if="tag.type===1"
        style="cursor: pointer"
        :key="tag"
        size="small"
        closable
        :disable-transitions="true"
        @close="removeFilterNode(i)"
        @click="editTransferByTag(tag,i)"
      >
        {{ formatTagText(tag) }}
      </el-tag>
      <el-popover
        v-else
        :key="tag"
        placement="bottom"
        trigger="click">
        <el-tag
          slot="reference"
          style="cursor: pointer"
          :key="tag"
          size="small"
          closable
          :disable-transitions="true"
          @close="removeFilterNode(i)"
        >
          {{ formatTagText(tag) }}
        </el-tag>
        <!--<el-input v-if="tag.type===1" v-model="filterData[i].value"></el-input>-->
        <el-select v-model="filterData[i].value" :key="tag" size="mini"
                   multiple
                   clearable
                   collapse-tags
                   filterable
                   class="button-new-tag"
                   :ref="'saveTagInput'+[i]">
          <el-option
            v-for="item in selectOptions(tag)"
            :key="item.value"
            :label="item.label"
            :value="{label:item.label, value: item.value}"
            filterable>
          </el-option>
        </el-select>
      </el-popover>
    </template>
    <el-cascader
      class="button-new-tag"
      v-model="cascaderValue"
      :options="options"
      size="mini"
      :props="{ expandTrigger: 'hover' }"
      filterable
      placeholder="添加筛选条件"
      @change="handleChangeCascader"
    ></el-cascader>
    <!--输入框搜索弹窗-->
    <el-dialog
      :visible.sync="searchDialogVisible"
      append-to-body
      :modal="false"
      width="500px"
      :title="searchDialogData.title"
      @close="clearDialogInput"
    >
      <cs-transfer ref="transferRef" :type="searchDialogData.label" v-model="searchValue"></cs-transfer>
      <span slot="footer" class="dialog-footer">
    <el-button size="mini" type="primary" @click="submitFilterQuery">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import CsTransfer from "@/components/CsFilterQueryForApi/components/CsTransfer";

export default {
  name: "CsFilterQueryForApi",
  props: {
    options: {
      type: Array,
      default() {
        // [{
        //   value: 'platform', // 唯一
        //   label: '媒体',
        //   children: [
        //     {
        //       value: 'a',
        //       label: '媒体1'
        //     }
        //   ]
        // }, {
        //   value: 'os',
        //   label: '系统'
        // }]
        return []
      }
    },
  },
  components: {
    CsTransfer
  },
  data() {
    return {
      cascaderValue: [],
      // 搜索传递框的多选配置，类似select组件配置
      roles: [],
      // 已选择原始数据，驱动tag组件生成
      filterData: [],
      // 搜索框弹窗
      searchDialogVisible: false,
      // 搜索框传递数据
      searchDialogData: {
        title: '',
        label: '', // 弹窗数值缓存
      },
      // 搜索弹窗数值
      searchValue: [],
      // 弹窗是否为修改
      isEdit: false,
      // 当前弹窗的索引
      currentQueryIndex: '',
    }
  },
  computed: {
    formatFilterData() {
      const data = new Object()
      this.filterData.forEach(item => {
        if (data.hasOwnProperty(item.label)) {
          // 去重
          data[item.label] = Array.from(new Set([...data[item.label].split(','), ...item.value.map(item => item.value)])).join(',')
        } else {
          data[item.label] = item.value.map(item => item.value).join(',')
        }
      })
      return data
    }
  },
  watch: {
    filterData: {
      handler: function (val, oldVal) {
        this.$emit('change', this.formatFilterData)
        // console.log(this.formatFilterData)
      },
      deep: true
    }
  },
  methods: {
    // 筛选条件改变
    handleChangeCascader(values) {
      const index = this.filterData.findIndex(item => {
        return item.label === values[0]
      })
      if (values.length === 1) {
        // 级联选择框一级选择
        this.isEdit = false
        this.searchValue = []
        this.searchDialogVisible = true
        this.searchDialogData.title = this.options.find(item => item.value === values[0]).label
        this.searchDialogData.label = values[0]
      } else if (values.length === 2) {
        // 级联选择二级菜单
        const group = this.options.find(item => item.value === values[0])
        if (index === -1) {
          this.filterData.push({
            label: values[0],
            value: group.children.filter(item => item.value === values[1]),
            type: 2 // 类型1为一级，类型2为二级
          })
        } else {
          if (!this.filterData[index].value.some(item => item.value === values[1])) {
            this.filterData[index].value.push(group.children.find(item => item.value === values[1]))
          }
        }
      }
      this.cascaderValue = []
    },
    // 选择菜单
    selectOptions(tag) {
      const group = this.options.find(item => item.value === tag.label)
      return group.children
    },
    // 格式筛选标签显示
    formatTagText(tag) {
      // 查询出类型
      const group = this.options.find(item => item.value === tag.label)
      // 类型下面子类过滤。变化。封装成字符串
      let values = ''
      if (tag.value instanceof Array) {
        values = tag.value.map(item => item.label).join('，')
      } else {
        values = tag.value
      }
      // 拼接 搜索类型：子类内容，子类内容
      let text = group.label + '：' + values
      if (text.length > 50) { // 限制50个字
        text = text.substr(0, 50) + '...'
      }
      return text
    },
    //移除搜索节点
    removeFilterNode(index) {
      this.filterData.splice(index, 1)
    },
    // 提交筛选条件
    submitFilterQuery() {
      this.searchDialogVisible = false
      if (this.isEdit) {
        if (this.searchValue.length === 0) {
          this.filterData.splice(this.currentQueryIndex, 1)
        } else {
          this.filterData[this.currentQueryIndex].value = this.searchValue
        }
      } else {
        if (this.searchValue.length === 0) return
        this.filterData.push({
          label: this.searchDialogData.label,
          value: this.searchValue,
          type: 1
        })
      }
      // console.log(this.filterData)
    },
    // 修改搜索标签
    editTransferByTag(tag, index) {
      this.isEdit = true
      this.currentQueryIndex = index
      this.searchValue = tag.value
      this.searchDialogVisible = true
    },
    // 清空弹窗输入内容
    clearDialogInput() {
      this.$refs.transferRef.searchTextLeft = ''
      this.$refs.transferRef.originData = []
      this.searchValue = []
    },
    // 清空筛选框
    clear() {
      this.filterData = []
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin-left: 10px;
  margin-bottom: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  margin-bottom: 10px;
}

</style>
